<template>
  <div class="wrapper">
    <Button type="default" class="back" @click="backMet()">
      <Icon type="ios-arrow-back" />
      {{ $t('user.back_text') }}
    </Button>
    <div class="edit-profile-main">
      <div class="title">{{ $t('assistant.user_info_text') }}</div>
      <Upload :show-upload-list="false" :headers="{
        'X-Access-Token': userToken,
        'lang': 'en_US'
      }" biz="chat" :data="{
        biz: 'custom'
      }" name="file" :disabled="uploadLoading" :max-size="3072" :before-upload="() => handleBeforeUpload()"
        :on-success="(response) => onSuccess(response)" :on-exceeded-size="() => handleMaxSize(file)"
        :action="uploadURL" :accept="'.png,.jpg,.jpeg'">
        <div class="loading-wrap" v-if="uploadLoading">
          <t-loading></t-loading>
        </div>
        <div v-if="imageUrl != '' && !uploadLoading" class="preview-img">
          <img class="upload-image" :src="computedImageUrl" alt="" />
          <img src="@/assets/images/user/camera.png" class="camera-icon" alt="">
          <div class="overlay"></div>
        </div>
      </Upload>
      <div class="line-sty">
        <div class="options-sty">
          <div class="label">{{ $t('assistant.nick_name') }}</div>
          <Input v-model="form.nikeName" class="input-sty" />
        </div>
        <div class="options-sty">
          <div class="label">{{ $t('assistant.user_id_label') }}</div>
          <Input v-model="form.id" disabled class="input-sty" />
        </div>
      </div>
      <div class="line-sty">
        <div class="options-sty">
          <div class="label">{{ $t('assistant.user_sex') }}</div>
          <Select v-model="form.sex" class="select-sty">
            <Option v-for="item in genderList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </div>
        <div class="options-sty">
          <div class="label">{{ $t('assistant.user_bir_text') }}</div>
          <DatePicker type="date" size="large" transfer class="pick-sty" v-model="form.birthday"
            @on-change="slDatePick">
          </DatePicker>
        </div>
      </div>
      <div class="line-sty">
        <div class="options-sty">
          <div class="label">{{ $t('assistant.user_info_email') }}</div>
          <Input v-model="displayedEmail" readonly class="input-sty only-sty">
          <Icon v-if="showFullEmail" type="md-eye" slot="suffix" class="md-eye" @click="toggleEmailVisibility" />
          <Icon v-if="!showFullEmail" type="md-eye-off" slot="suffix" class="md-eye" @click="toggleEmailVisibility" />
          </Input>
        </div>
        <div class="options-sty" v-if="false">
          <div class="label">{{ $t('personal.PhoneNumber') }}</div>
          <Input v-model="form.mobile" class="input-sty" />
        </div>
      </div>

      <div v-if="false">
        <div class="tit">
          <div class="text">账号认证</div>
        </div>
        <div class="sub-tit">账号认证</div>
        <div v-for="(item, index) in newBindArr" :key="index">
          <div class="list-task" :style="statusStyle(item.userTaskStatus)">
            <div class="left">
              <img v-if="item.taskType == '5'" src="@/assets/images/user/task_img5.png" class="img-icon" alt="">
              <img v-if="item.taskType == '6'" src="@/assets/images/user/task_img6.png" class="img-icon" alt="">
              <div class="task-info">
                <div class="task-text">{{ item.taskName }}</div>
                <div class="reward">
                  <span class="condition">+{{ item.goldCoinNum }}</span>
                  <img src="@/assets/images/promote/coin.png" class="coin-icon" alt="">
                </div>
              </div>
            </div>
            <div class="right">
              <!-- 未完成 -->
              <Button v-if="item.taskType == '5' && item.userTaskStatus == '0'" type="primary" class="do-task-btn"
                @click="bindDiscordMet()">去认证</Button>
              <Button v-if="item.taskType == '6' && item.userTaskStatus == '0'" type="primary" class="do-task-btn"
                @click="bindPhoneMet()">去绑定</Button>
              <!-- 已完成 -->
              <Button v-if="item.userTaskStatus == '1'" type="primary" class="pick-up-btn"
                @click="pickUpMet()">领取奖励</Button>
              <!-- 已领取 -->
              <Button v-if="item.userTaskStatus == '2'" type="primary" class="received-btn">已领取</Button>
            </div>
          </div>
          <Divider class="interval-sty" v-if="newBindArr.length > 1 && index < 1" />
        </div>
      </div>

      <div class="handle-sty">
        <Button type="primary" class="save-btn" @click="saveMet()">{{ $t('assistant.save_btn_text') }}</Button>
        <Button class="cancel-btn" @click="backMet()">{{ $t('pay.cancel') }}</Button>
      </div>

    </div>

    <!-- Discord账号认证 -->
    <bind-discord-pop ref="discordRef"></bind-discord-pop>
    <!-- 绑定手机号 -->
    <bind-phone-number ref="bindPhoneRef"></bind-phone-number>

  </div>
</template>
<script>
import { mapState } from "vuex";
import { commonUpload } from "@/api/sys";
import TLoading from "@/components/t-loading";
import { editorMyInfo, getTaskNewList, getReceive } from "@/api/user";
import { debounce } from "@/common/common";
import BindDiscordPop from "./components/bind-discord-pop.vue";
import BindPhoneNumber from "./components/bind-phone-number.vue";
export default {
  components: { TLoading, BindDiscordPop, BindPhoneNumber },
  data() {
    return {
      form: {
        birthday: '2001-01-01'
      },
      genderList: [
        {
          value: '0',
          label: '未知'
        },
        {
          value: '1',
          label: '男'
        },
        {
          value: '2',
          label: '女'
        },
      ],
      localImageUrl: require('@/assets/images/home/top_nav_user.svg'),
      uploadLoading: false,
      imageUrl: '',
      showFullEmail: false,
      userToken: localStorage.getItem("USER_TOKEN"),
      uploadURL: commonUpload(),
      newBindArr: []
    }
  },
  watch: {
    userInfo: {
      handler(newVal) {
        if (newVal) {
          this.imageUrl = newVal.avatar;
          this.form = newVal;
          this.form.birthday = newVal.birthday ? newVal.birthday : '2000-01-01';
        }
      },
      immediate: true // 立即执行一次该 handler 方法，以检查初始值是否满足条件
    }
  },
  created() {
    this.getTaskNew();
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    }),
    computedImageUrl() {
      // 如果 imageUrl 有值，使用 imageUrl，否则使用本地图片的路径
      return this.imageUrl ? this.imageUrl : this.localImageUrl;
    },
    displayedEmail() {
      if (this.showFullEmail) {
        return this.form.email;
      } else {
        if (this.form && this.form.email) {
          // 假设邮箱格式为 xxx@yyy.zzz，隐藏部分内容
          const parts = this.form.email.split('@');
          const username = parts[0];
          const domain = parts[1];
          const hiddenUsername = username.slice(0, 2) + '***********';
          return hiddenUsername + '@' + domain;
        } else {
          return '';
        }
      }
    }
  },
  methods: {
    backMet() {
      this.$router.push('/user/center');
    },
    getTaskNew() {
      getTaskNewList().then((res) => {
        let data = res.result;
        // 绑定任务
        this.newBindArr = data.filter(item => {
          return item.taskType === '5' || item.taskType === '6'
        });
      })
    },
    // 已领取设置透明度
    statusStyle(status) {
      return {
        opacity: status === '2' ? 0.4 : ''
      };
    },
    // Discord账号认证
    bindDiscordMet() {
      this.$refs.discordRef.open();
    },
    // 绑定手机号
    bindPhoneMet() {
      this.$refs.bindPhoneRef.open();
    },
    slDatePick(c, v) {
      this.form.birthday = c;
    },
    toggleEmailVisibility() {
      this.showFullEmail = !this.showFullEmail; // 切换显示状态
    },
    handleMaxSize(file) {
      this.uploadLoading = false;
      this.$Message.error(`File ${file.name} is too large, no more than 3M.`);
    },
    onSuccess(response) {
      // 上传成功
      this.uploadLoading = false;
      if (response.code == 0 || response.code == 200 || response.code == 201) {
        this.$webToastObj({
          message: this.$t('assistant.upload_ava_success'),
          time: 2000
        });
        let data = response.result;
        this.imageUrl = data.url;
      } else {
        this.$webToastObj({
          message: response.message,
          time: 2000
        });
      }
    },
    onError() {
      this.$webToastObj({
        message: this.$t('user.uploadFailure'),
        time: 2000
      });
    },
    handleBeforeUpload() {
      this.uploadLoading = true;
    },
    saveMet: debounce(function () {
      // if (isNaN(this.form.mobile)) {
      //   this.$Message.error('请输入正确格式的手机号!');
      //   return;
      // }

      editorMyInfo({
        nikeName: this.form.nikeName,
        avatar: this.imageUrl,
        birthday: this.form.birthday,
        sex: this.form.sex,
        // mobile: this.form.mobile
      }).then((res) => {
        if (res.code == 200) {
          this.$store.dispatch("getUserInfo");
          this.$router.push('/user/center');
          this.$Message.success(res.message);
        }
      })
    }),
    // 领取成功
    pickUpMet() {
      this.$webToastObj({
        message: '领取成功！',
        time: 2000
      });
    }
  }
}
</script>
<style lang="less" scoped>
.wrapper {

  .back {
    font-weight: 400;
    font-size: 16px;
    color: #767B93;
    line-height: 19px;
  }

  .edit-profile-main {
    padding: 30px;
    border-radius: 20px;
    background: #FFF;
    margin-top: 16px;
  }

  .back:focus {
    box-shadow: none;
  }

  .back:hover {
    border-color: #767b9333;
  }

  .preview-img {
    margin-bottom: 24px;
    position: relative;
    cursor: pointer;

    .upload-image {
      width: 80px;
      height: 80px;
      border-radius: 50%;
    }

    .overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 80px;
      height: 80px;
      display: block;
      border-radius: 50%;
      background-color: rgba(0, 0, 0, 0.1);
    }

    .camera-icon {
      width: 24px;
      height: 24px;
      position: absolute;
      top: 28px;
      left: 28px;
      z-index: 2;
      cursor: pointer;
    }
  }

  .title {
    font-weight: 600;
    font-size: 20px;
    color: #1E1714;
    line-height: 23px;
    margin-bottom: 28px;
  }

  .line-sty {
    display: flex;
    gap: 24px;
    margin-bottom: 32px;

    .options-sty {
      .label {
        font-weight: 400;
        font-size: 16px;
        color: #767B93;
        line-height: 16px;
        margin-bottom: 12px;
      }

      .input-sty {
        width: 373px;

        :deep(.ivu-input) {
          height: 48px;
          border-radius: 8px 8px 8px 8px;
          padding-left: 16px;
          font-size: 16px;
          line-height: 18px;
        }

        .md-eye {
          color: #AEB0B9;
          font-size: 20px;
          margin-right: 16px;
          cursor: pointer;
        }
      }

      .only-sty {
        :deep(.ivu-input) {
          background-color: #F7F9FB;
        }

        :deep(.ivu-input:hover) {
          border-color: #dcdee2;
        }

        :deep(.ivu-input:focus) {
          border-color: #dcdee2;
        }
      }

      .select-sty {
        width: 373px;

        :deep(.ivu-select-selection) {
          height: 48px;
          border-radius: 8px 8px 8px 8px;
          padding-left: 16px;
          font-size: 16px;
          line-height: 18px;

          .ivu-select-placeholder {
            height: 48px;
            border-radius: 8px 8px 8px 8px;
            font-size: 16px;
            line-height: 48px;
          }

          .ivu-select-selected-value {
            height: 48px;
            border-radius: 8px 8px 8px 8px;
            font-size: 16px;
            line-height: 48px;
          }
        }
      }

      .pick-sty {
        width: 373px;

        :deep(.ivu-input) {
          height: 48px;
          border-radius: 8px 8px 8px 8px;
          font-size: 16px;
          line-height: 48px;
          padding-left: 16px;
        }
      }
    }
  }

  .tit {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;

    .text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 600;
      font-size: 20px;
      color: #1E1714;
      line-height: 23px;
    }
  }

  .sub-tit {
    font-weight: 400;
    font-size: 16px;
    color: #AEB0B9;
    line-height: 22px;
    margin-bottom: 24px;
  }

  .list-task {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .left {
      display: flex;
      align-items: center;

      .img-icon {
        width: 48px;
        height: 48px;
      }

      .task-info {
        margin-left: 16px;

        .task-text {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 16px;
          color: #1E1714;
          line-height: 19px;
        }

        .reward {
          margin-top: 11px;
          display: inline-flex;
          align-items: center;

          .condition {
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            font-size: 16px;
            color: #AEB0B9;
            line-height: 19px;
            margin-right: 6px;
          }

          .coin-icon {
            width: 16px;
            height: 16px;
          }
        }
      }
    }

    .right {
      .pick-up-btn {
        min-width: 119px;
        padding: 0 28px;
        height: 42px;
        background: #FFD333;
        border-radius: 40px;
        border: none;
        font-size: 18px;
        color: #452E00;
      }

      .do-task-btn {
        min-width: 119px;
        padding: 0 28px;
        height: 42px;
        background: #F5F6FA;
        border-radius: 40px;
        border: none;
        font-size: 18px;
        color: #452E00;
      }

      .do-task-btn:focus {
        box-shadow: 0 0 0 2px #F5F6FA;
      }

      .received-btn {
        min-width: 119px;
        padding: 0 28px;
        height: 42px;
        background: #F5F6FA;
        border-radius: 40px;
        border: none;
        font-size: 18px;
        color: #452E00;
      }

      .received-btn:focus {
        box-shadow: none;
      }

      .received-btn:hover {
        cursor: default;
      }
    }
  }

  .interval-sty {
    margin: 26px 0;
  }

  .handle-sty {
    display: flex;
    align-items: center;
    gap: 24px;
    margin-top: 58px;

    .save-btn {
      min-width: 124px;
      height: 48px;
      background-color: #FF186B;
      font-weight: 600;
      font-size: 18px;
      color: #FFFFFF;
      line-height: 21px;
      border-radius: 8px;
    }

    .cancel-btn {
      min-width: 124px;
      height: 48px;
      font-weight: 600;
      font-size: 18px;
      color: #1E1714;
      line-height: 21px;
      border-radius: 8px;
    }

    .cancel-btn:hover {
      border-color: #e3e5e8;
    }

    .cancel-btn:focus {
      box-shadow: 0 0 0 1px #e3e5e846;
    }
  }
}
</style>
